from django.http import JsonResponse
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .models import WebInfo, WebInfoSerializer


# 管理端：获取和修改网站信息
class AdminWebInfoView(APIView):
    def get(self, request):
        """
        管理端获取网站信息
        """
        web_info = WebInfo.objects.first()
        if not web_info:
            return Response({
                'code': 404,
                'message': '网站信息不存在',
                'ok': 'false'
            }, status=status.HTTP_404_NOT_FOUND)

        serializer = WebInfoSerializer(web_info)
        return Response({
            'code': 200,
            'message': '成功',
            'data': serializer.data,
            'ok': 'true'
        }, status=status.HTTP_200_OK)

    def put(self, request):
        """
        管理端修改网站信息
        """
        web_info = WebInfo.objects.first()
        if not web_info:
            return Response({
                'code': 404,
                'message': '网站信息不存在',
                'ok': 'false'
            }, status=status.HTTP_404_NOT_FOUND)

        serializer = WebInfoSerializer(web_info, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response({
                'code': 200,
                'message': '成功',
                'data': serializer.data,
                'ok': 'true'
            }, status=status.HTTP_200_OK)
        return Response({
            'code': 400,
            'message': '数据无效',
            'ok': 'false',
            'errors': serializer.errors
        }, status=status.HTTP_400_BAD_REQUEST)


# 博客端：获取网站信息
class BlogWebInfoView(APIView):
    def get(self, request):
        """
        博客端获取网站信息
        """
        web_info = WebInfo.objects.first()
        if not web_info:
            return Response({
                'code': 404,
                'message': '网站信息不存在',
                'ok': 'false'
            }, status=status.HTTP_404_NOT_FOUND)

        serializer = WebInfoSerializer(web_info)
        return Response({
            'code': 200,
            'message': '成功',
            'data': serializer.data,
            'ok': 'true'
        }, status=status.HTTP_200_OK)
